<?php

class csPager {
	public $cs_params;
	public $pass_params;
	public $limit = 20;
	public $limit_pages = 20;
	public $all_rows = 0;
	public $pager_tpl = null;
	
	protected $pages_tbl;
	protected $pages_count = null;
	protected $current_page = null;

	public function __construct(&$cs_params = null, &$pass_params = null, $params = null) {
		if (is_array($cs_params)) {
			$this -> cs_params = $cs_params;
		} else {
			$this -> cs_params = array(
			);
		}
		if (is_array($pass_params)) {
			$this -> pass_params = $pass_params;
		} else {
			$this -> pass_params = array(
			);
		}
		if (isset($params['limit']))
			$this -> limit = $params['limit'];
		if (isset($params['limit_pages']))
			$this -> limit_pages = $params['limit_pages'];
		if (isset($params['all_rows']))
			$this -> all_rows = $params['all_rows'];
		if (isset($params['pager_tpl']))
			$this -> pager_tpl = $params['pager_tpl'];
		
		$this -> pages_tbl = array(
		);
	}

	public function do_paginate() {
		$this -> pages_tbl = array(
		);
		
		if ($this -> all_rows < 1) {
			$this -> pages_count = 1;
			$this -> current_page = 1;
			return;
		}
		
		$this -> pages_count = ceil($this -> all_rows / $this -> limit);
		$this -> current_page = ((isset($this -> cs_params['page']) && $this -> cs_params['page'] && $this -> cs_params['page'] <= $this -> pages_count) ? $this -> cs_params['page'] : 1);
		if ($this -> pages_count <= 1)
			return;
		
		for ($i = 1; $i <= $this -> pages_count; $i ++) {
			$this -> pages_tbl[$i] = array(
				'page' => $i, 
				'link' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
					'page' => $i
				)), 
				'current' => ($i == $this -> current_page ? true : false)
			);
		}
	}

	public function get_pages_count() {
		return $this -> pages_count;
	}

	public function get_current_page() {
		return $this -> current_page;
	}

	public function display() {
		//TODO - jesli liczba podstron > pages_limit to wyciac czesc linkow i zasapic 3 kropkami
		//TODO - dodac strzalki - nastepna, poprzednia podstrona
		if ($this -> all_rows == 1) {
			$pager_info = translate('Following list includes 1 record');
		} else {
			$pager_info = sprintf(translate('Following list includes %s records'), $this -> all_rows);
		}
		if ($this -> pages_count > 1) {
			$pager_info .= ' ' . sprintf(translate('displayed on %s subpages'), $this -> pages_count);
		}
		
		if ($this -> pager_tpl) {	//TODO - jesli jest templejt to z niego skorzystac, docelowo ma byc templejt
		} else {
			echo $pager_info . "<br />\n";
			foreach ($this -> pages_tbl as $page) {
				if ($page['current']) {
					echo $page['page'] . '&nbsp;';
				} else {
					echo '<a href="' . $page['link'] . '">' . $page['page'] . '</a>&nbsp;';
				}
			}
		}
	}
}
?>